//
//  YTTLocationTool.m
//  跑圈儿
//
//  Created by dllo on 16/4/28.
//  Copyright © 2016年 唐康. All rights reserved.
//

#import "YTTLocationTool.h"
#import <CoreLocation/CoreLocation.h>
#import <UIKit/UIKit.h>

@interface YTTLocationTool ()<CLLocationManagerDelegate>


@property(nonatomic, strong) CLLocationManager *manager;
@property(nonatomic, strong) saveLocationBlock  savelocationBlock;
@property(nonatomic, strong) NSString *cityName;

@end

@implementation YTTLocationTool

+ (id)sharedLoactionManager{
    static YTTLocationTool *locationManager = nil;
    if (!locationManager) {
        locationManager = [[YTTLocationTool alloc]init];
    }
    return locationManager;
}



//重写init方法初始化manager对象/征求用户同意
- (instancetype)init
{
    if (self = [super init]) {
        self.manager = [CLLocationManager new];
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [self.manager requestWhenInUseAuthorization];
        }
        
        self.manager.delegate = self;
    }
    
    return self;
}

+ (void)getUserLocation:(saveLocationBlock)locationBlock
{
    
    YTTLocationTool *locationMangaer = [YTTLocationTool sharedLoactionManager];
    return[locationMangaer getUserLoaction:locationBlock];
}

- (void)getUserLoaction:(saveLocationBlock)locationBlock
{
    if (![CLLocationManager locationServicesEnabled]) {
        
        return;
    }
    _savelocationBlock = [locationBlock copy];
    self.manager.distanceFilter = 100;
    [self.manager startUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *location = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error) {
            NSString *cityName = placemarks.lastObject.addressDictionary[@"City"];
            NSString *str = [cityName substringToIndex:cityName.length -1];
            _savelocationBlock(location.coordinate.latitude,location.coordinate.longitude,str);
            
        }
        
    }];

    
}


@end
